﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using InTheHand.Net;
using InTheHand.Net.Sockets;
using SensorDrone.Net;
using SensorDrone.Net.Extensions;
using System.Reactive.Linq;
namespace SensorDrone
{
    class Program
    {
        public CancellationTokenSource CancellationToken = new CancellationTokenSource();
        private IDisposable _subscriber;
        private IObservable<Reading> _observable; 
        static void Main(string[] args)
        {
            Program program = new Program();
            program.Run();
            Console.ReadKey();
            program.CancellationToken.Cancel();
            Console.ReadKey();
        }

        async private void Run()
        {
            SensorDroneProvider provider = new SensorDroneProvider();
            var drones = await provider.ScanAsync();
            var sensorDrone = drones.First();

            using (sensorDrone)
            {
                Console.WriteLine("{0},{1}",sensorDrone.Address,sensorDrone.Name);
                await sensorDrone.ConnectAsync();
                Console.WriteLine("{0},{1}", sensorDrone.Address, sensorDrone.Version);
                await sensorDrone.EnableAllAsync();
                List<string> sensors = sensorDrone.Sensors.Where(sensor => sensor.IsSi).Select(sensor => sensor.Name).ToList();
                _observable = sensorDrone.AsObservable(sensors);
                var colorSubscription = sensorDrone.AsObservable(new[] { "RGBC" }).Subscribe(OnColorChange);
                foreach (var sensor in sensors)
                {
                    string sensor1 = sensor;
                    var subscriber = _observable.Where(reading => reading.Name == sensor1).Timestamp().Subscribe(sensorDrone_Reading, OnException);
                }
                
                Console.ReadKey();
            }
            
        }

        private void OnColorChange(Reading reading)
        {

        }

        void sensorDrone_Reading(Timestamped<Reading> reading)
        {
            Console.WriteLine("{0} {1}:{2} {3}",reading.Timestamp,reading.Value.Name,reading.Value.Value,reading.Value.Unit);
        }

        private void OnException(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        void sensorDrone_Reading2(Timestamped<Reading> reading)
        {
            Console.WriteLine("{0} {1}:{2} {3}", reading.Timestamp, reading.Value.Name, reading.Value.Value, reading.Value.Unit);
        }
    }
}
